#!/home/wheeltec/archiconda3/envs/yolov5-Lite/bin/python

import cv2
import time
import rospy
import pyttsx3
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError

import torch
from numpy import random
import torch.backends.cudnn as cudnn
from models.experimental import attempt_load
from utils.datasets import LoadImages, LoadStreams, LoadWebcam
from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, \
    scale_coords, xyxy2xywh, strip_optimizer, set_logging
from utils.plots import plot_one_box
from utils.torch_utils import select_device, time_synchronized

class YOLOv5_Lite:
    def __init__(self, opt):
        self.view_img = opt.view_img
        source, weights, imgsz = opt.source, opt.weights, opt.img_size
        self.webcam = source.isnumeric()

        self.classes=opt.classes
        self.augment=opt.augment
        self.iou_thres=opt.iou_thres
        self.agnostic=opt.agnostic_nms
        self.conf_thres=opt.conf_thres

        self.result_list = []


        # Initialize
        set_logging()
        self.device = select_device(opt.device)
        self.half = self.device.type != 'cpu'  # half precision only supported on CUDA  在CUDA计算中启用半精度浮点数

        # Load model
        self.model = attempt_load(weights, map_location=self.device)  # load FP32 model
        stride = int(self.model.stride.max())  # model stride
        imgsz = check_img_size(imgsz, s=stride)  # check img_size
        if self.half:
            self.model.half()  # to FP16

        # Second-stage classifier Disabled
        # Set Dataloader
        if self.webcam:
            self.view_img = check_imshow()
            cudnn.benchmark = True  # set True to speed up constant image size inference
            # self.dataset = LoadWebcam(source, img_size=imgsz, stride=stride)
            self.dataset = LoadStreams(source, img_size=imgsz, stride=stride)
        else:
            self.dataset = LoadImages(source, img_size=imgsz, stride=stride)

        # Get names and colors
        self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names
        self.colors = [[random.randint(0, 255) for _ in range(3)] for _ in self.names]

        # Run inference
        if self.device.type != 'cpu':
            self.model(torch.zeros(1, 3, imgsz, imgsz).to(self.device).type_as(next(self.model.parameters())))  # run once

    def detect_img(self, img, im0s):
        """
        检测图像的内容并返回检测到的类名和画框后的图片
            img:处理后的图片 \r
            im0s:未处理的图片（组）
        """
        s = ''                                          # 初始化输出字符串，后续操作都为自增运算符，需要先声明
        img = torch.from_numpy(img).to(self.device)     # 输入的numpy数组转换为张量并复制到设备中用于计算
        img = img.half() if self.half else img.float()  # uint8 to fp16/32 8位整数转换为半浮点或者浮点数
        img /= 255.0  # 0 - 255 to 0.0 - 1.0            # img图像数值归一化
        if img.ndimension() == 3:                       # 对于三维张量进行维度扩充
            img = img.unsqueeze(0)                      # 对于三维张量进行维度扩充，填充批次维度，适应模型输入要求，方便进行模型的前向传播计算

        # Inference
        t1 = time_synchronized()                        # 记录操作前的时间
        pred = self.model(img, augment=self.augment)[0] # 利用模型对于张量进行推理预测计算

        # Apply NMS                                     # 对结果进行进行非最大值抑制计算
        pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, classes=self.classes, agnostic=self.agnostic)
        t2 = time_synchronized()                        # 记录操作后的时间

        # Apply Classifier Disabled
        # Process detections
        for i, det in enumerate(pred):                  # 遍历向量获取预测结果
            target_list = []
            if self.webcam:  # batch_size >= 1          # 相机读取下需要对于每个批次生成原图像的副本
                im0 =im0s[i].copy()
            else:
                im0 = im0s

            # s += '%gx%g ' % img.shape[2:]             # 打印分辨率 480*640
            if len(det):
                gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh 归一化因子，用于将预测框的坐标从归一化坐标转换为原始坐标
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

                # Print results
                for c in det[:, -1].unique():
                    n = (det[:, -1] == c).sum()  # detections per class
                    s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, "  # 添加类名

                # Write results
                for *xyxy, conf, cls in reversed(det):
                    # 识别结果格式化
                    xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                    # line = (cls, *xywh, conf)  # label format
                    # print(('%g ' * len(line)).rstrip() % line + '\n')
                    conf = float(f'{conf}')
                    target_list = [self.names[int(cls)],round(conf,3),time.time()]
                    rospy.loginfo(f'{target_list}')
                    self.result_list.append(self.names[int(cls)])

                    if self.view_img:  # Add bbox to image
                        label = f'{self.names[int(cls)]} {conf:.2f}'
                        plot_one_box(xyxy, im0, label=label, color=self.colors[int(cls)], line_thickness=3)
            else:
                    self.result_list.append('_none_')
            # Print time (inference + NMS)
            print(f'{s}Done. ({t2 - t1:.3f}s)') # 打印类名和时间

        if len(self.result_list) > 256:                     # 限制缓存列表长度，以节省内存使用
            self.result_list = self.result_list[-256:]

        return self.result_list[-1], im0


    def get_stable_target(self):
        '''
        检测最后十个目标中稳定出现的类内容
        '''
        result = '_null_'
        if len(self.result_list) > 10:
            cnt_list = self.result_list[-10:]
        else:
            cnt_list = self.result_list

        if cnt_list.count(cnt_list[-1]) > 9:        # 稳定出现超过
            result = cnt_list[-1]

        return result    # 返回列表中出现最多次数的类名  

    def init_ros_node(self):
        rospy.init_node("yolov5l_node")
        self.navi_pub = rospy.Publisher("/waterplus/navi_waypoint", String, queue_size=1)
        self.res_sub = rospy.Subscriber("/waterplus/navi_result", String, self.NavResultCb, queue_size=1)
        self._pub = rospy.Publisher("/result_ripe", Image, queue_size=0)
        self._cv_bridge = CvBridge()
        self.waypoint_msg = String()
        self.action_done = True
        self.waypoint_msg.data = ""
        self.current_target = ""

    def NavResultCb(self, msg):
        # rospy.logwarn(f"导航结果{msg.data}")
        if msg.data == "done":
            # 由于action_done之前，程序不会对waypoint_msg进行更改，所以这里直接使用缓存的data内容赋值current_target
            self.current_target = self.waypoint_msg.data
            self.action_done = True
            line = "goal reached" #要播报的内容
            self.engine.say(line)
            self.engine.runAndWait()
        else:
            self.current_target = self.waypoint_msg.data
            rospy.logerr("Navi goal result abnormal")
            self.action_done = True
            # exit(29)

    def tts_init(self):
        self.engine = pyttsx3.init()
        # 改变语速  范围为0-200   默认值为200
        rate = self.engine.getProperty('rate')  #获取当前语速
        self.engine.setProperty('rate', rate-60)

    def run(self):
            self.init_ros_node()
            self.tts_init()
            target_change = False
            t0 = time.time()
            for _path_, img, im0s, vid_cap in self.dataset:
                _,img = self.detect_img(img, im0s)          # 这里会返回实时的类名和框选后的图像，目前没有用上类名
                if self.action_done:
                    rospy.loginfo_throttle(1, f'current target is {_}')
                # view results 显示结果
                if self.view_img:
                    cv2.imshow('Result images', img)
                    cv2.waitKey(1)  # 1 millisecond
                # 发布结果图像
                try:
                    self._pub.publish(self._cv_bridge.cv2_to_imgmsg(img, "passthrough"))
                except CvBridgeError as e:
                    rospy.logerr(e) 
                
                cls = self.get_stable_target()
                rospy.sleep(0.01)
                if not self.action_done:            # 航点到达之前不需要进行下一个航点的发送
                    continue
                
                # 匹配类信息与航点信息
                if cls == 'candy':
                    self.waypoint_msg.data = "candy"
                elif cls == 'tissue':
                    self.waypoint_msg.data = "tissue"
                elif cls == 'cake':
                    self.waypoint_msg.data = "cake"
                elif cls == 'mint':
                    self.waypoint_msg.data = "mint"
                elif cls == '_none_':
                    self.waypoint_msg.data = "home"
                elif cls == '_null_':
                    self.waypoint_msg.data = "-"
                rospy.loginfo(f'waypoint change from {self.current_target} to {self.waypoint_msg.data}')
                # 如果 不是首次运行 且 当前位置和要发送的位置不同，则发送新目标
                if not self.waypoint_msg.data == "-" and not self.waypoint_msg.data == self.current_target:
                    self.navi_pub.publish(self.waypoint_msg)
                    self.action_done = False
            print(f'All Done. ({time.time() - t0:.3f}s)')


class Static_Options(object):
    def __init__(self):
        self.weights = rospy.get_param('/yolov5Lite/path') + '/scripts/models/best.pt'
        self.source = '0'
        self.img_size = 640
        self.conf_thres = 0.45
        self.iou_thres = 0.5
        self.device = '0'
        self.view_img = True
        self.classes = [0,1,2,3]
        self.agnostic_nms = False
        self.augment = False
        self.update = False


if __name__ == '__main__':
    opt = Static_Options()
    print(opt)
    check_requirements(exclude=('pycocotools', 'thop'))

    yolov5_l = YOLOv5_Lite(opt)

    with torch.no_grad():
        if opt.update:  # update all models (to fix SourceChangeWarning)
            for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
                yolov5_l.run()
                strip_optimizer(opt.weights)
        else:
            yolov5_l.run()
